
#include<iostream>
#include<map>
#include<vector>
class Listener
{
public:
	Listener(std::string name)
		:mname(name) {}
	virtual void handleMessage(int message) = 0;
protected:
	std::string mname;
};
class Listener1 : public Listener
{
public:
	Listener1(std::string name) :Listener(name) {}
	void handleMessage(int message)
	{
		switch (message)
		{
		case 1:
			std::cout << mname << " : 1 " << "has been  solved! " << std::endl;
			break;
		case 2:
			std::cout << mname << " : 2 " << "has been  solved! " << std::endl;
			break;
		default:
			std::cout << mname << " no interested this message!" << std::endl;
			break;
		}
	}
};
class Listener2 : public Listener
{
public:
	Listener2(std::string name) :Listener(name) {}
	void handleMessage(int message)
	{
		switch (message)
		{
		case 2:
			std::cout << mname << " : 2 " << "has been  solved! " << std::endl;
			break;
		case 3:
			std::cout << mname << " : 3 " << "has been  solved! " << std::endl;
			break;
		default:
			std::cout << mname << " no interested this message!" << std::endl;
			break;
		}
	}
};
 
class Listener3 : public Listener
{
public:
	Listener3(std::string name) :Listener(name) {}
	void handleMessage(int message)
	{
		switch (message)
		{
		case 1:
			std::cout << mname << " : 1 " << "has been  solved! " << std::endl;
			break;
		case 3:
			std::cout << mname << " : 3 " << "has been  solved! " << std::endl;
			break;
		default:
			std::cout << mname << " no interested this message!" << std::endl;
			break;
		}
	}
};
 
class Oberseve
{
public:
	void notify(int message)//某一事件发生；
	{
		std::map<int, std::vector<Listener*>>::iterator fit = mymap.find(message);
		if (fit != mymap.end())//有感兴趣的监听者 
		{
			std::vector<Listener*>::iterator it = fit->second.begin();//vector迭代器
			while (it != fit->second.end())
			{
				//消息通知    调用对方的接口  
				(*it)->handleMessage(message);
				it++;
			}
		}
		else//没感兴趣的监听者 
		{
			std::cout << "no listener interested this message!" << std::endl;
		}
	}
	void registerMessage(int message, Listener* pl)//让观察者观察某一事件
	{
		std::map<int, std::vector<Listener*>>::iterator fit = mymap.find(message);
		if (fit != mymap.end())//找到了 该事件已经注册  插入监听者集合
		{
			fit->second.push_back(pl);
		}
		else//没找到  map 插入一个关系
		{
			std::vector<Listener*> vec;
			vec.push_back(pl);
			mymap[message] = vec;
		}
	}
private:
	std::map<int, std::vector<Listener*>> mymap;//事件 监听者
};
 
int main()
{
	Listener1 l1("listener1");
	Listener2 l2("listener2");
	Listener3 l3("listener3");
 
	Oberseve ob;
 
	ob.registerMessage(1, &l1);//表示1号监听者对1号事件感兴趣
	ob.registerMessage(2, &l1);//表示2号监听者对1号事件感兴趣
	ob.registerMessage(2, &l2);//表示2号监听者对2号事件感兴趣
	ob.registerMessage(3, &l2);//表示3号监听者对2号事件感兴趣
	ob.registerMessage(1, &l3);//表示3号监听者对1号事件感兴趣
	ob.registerMessage(3, &l3);//表示3号监听者对3号事件感兴趣
 
	ob.notify(1);//事件1发生
	ob.notify(2);//事件2发生
	ob.notify(3);//事件3发生
	ob.notify(4);//事件4发生
	return 0;
}